import ensemblerobot
import midi

Defaults = {
    'channel':0,
    'solenoid':60,
    'light':0,
    'delay': (0.061035,0.061035),
}

class Beatblock(ensemblerobot.EnsembleRobot):
    _defaults = Defaults

    ## Delay
    def calculate_msdelay(self, velocity):
        low, high = self.delay
        delay_in_sec = low + (high - low) * (velocity / float(0x7f))
        msdelay = delay_in_sec * 1000
        return int(msdelay)

    def calculate_tickdelay(self, velocity, tick, stream):
        tempoev = stream.tempomap.get_tempo(tick)
        tempo = tempoev.tempo
        resolution = stream.resolution
        low, high = self.delay
        delay_in_sec = low + (high - low) * (velocity / float(0x7f))
        beats_per_sec = tempo / 60.0
        beats_per_delay = beats_per_sec * delay_in_sec
        ticks_per_delay = int(beats_per_delay * resolution)
        return int(ticks_per_delay)

    ## Lowlevel
    def light_on(self, tick):
        velocity = 0x7f
        lpitch = self.light
        noteon = self._new_note_on(lpitch, velocity, tick)
        return noteon

    def light_off(self, tick):
        lpitch = self.light
        noteoff = self._new_note_off(lpitch, tick)
        return noteoff

    def note_on(self, tick):
        velocity = 0x7f
        spitch = self.solenoid
        noteon = self._new_note_on(spitch, velocity, tick)
        return noteon

    def note_off(self, tick):
        spitch = self.solenoid
        noteoff = self._new_note_off(spitch, tick)
        return noteoff

    ## Midlevel
    def light_pair(self, tickon, tickoff, stream):
        noteon = self.light_on(tickon)
        stream.add_event(noteon)
        noteoff = self.light_off(tickoff)
        stream.add_event(noteoff)

    def note_pair(self, velocity, tick, stream):
        noteon = self.light_on(tick)
        stream.add_event(noteon)
        tdelay = self.calculate_tickdelay(velocity, tick, stream)
        noteoff = self.light_off(tick + tdelay)
        stream.add_event(noteoff)

    ## Highlevel
    def note(self, velocity, tick, stream):
        ldelay = self.calculate_tickdelay(velocity, tick, stream)
        self.light_pair(tick, tick+ldelay, stream)
        self.note_pair(velocity, tick, stream)
